package top.kwanghuee.shop.order.service.impl;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Service;
import top.kwanghuee.domain.Order;
import top.kwanghuee.domain.Product;
import top.kwanghuee.shop.order.mapper.OrderMapper;
import top.kwanghuee.shop.service.OrderService;
import top.kwanghuee.shop.service.ProductService;

import javax.annotation.Resource;

/**
 * @author: kwanghuee
 * @date: 2020/9/11 13:42
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderMapper orderMapper;

    @Reference(mock = "top.kwanghuee.shop.order.service.impl.ProductServiceMock")
    private ProductService productService;

    @Override
    public Order createOrder(int pid) {
        Product product = productService.findByPid(pid);

        log.info("查询到{}号商品的信息--->{}", pid, JSON.toJSONString(product));

        Order order = new Order();
        order.setUid(1)
                .setUsername("iu")
                .setPid(pid)
                .setPname(product.getPname())
                .setPprice(product.getPprice())
                .setNumber(1);
        orderMapper.save(order);
        return order;
    }

    @Override
    public int createOrder2(int pid) {
        Product product = productService.findByPid(pid);

        log.info("查询到{}号商品的信息--->{}", pid, JSON.toJSONString(product));
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("创建订单成功");

        return 0;
    }

    /**
     * @SentinelResource 定义一个资源
     * 定义当资源内部发生异常的时候的处理逻辑
     * blockHandler     定义当资源内部发生了BlockException应该进入的方法
     * fallback         定义当资源内部发生了Throwable应该进入的方法
     */
    @SentinelResource(
            value = "message",
            blockHandlerClass = OrderServiceImplBlockHandler.class,
            blockHandler = "blockHandler",
            fallbackClass = OrderServiceImplFallBack.class,
            fallback = "fallback"
    )
    @Override
    public String message(String msg) {
        return msg;
    }
}
